import bean.ListNode;

/**
 * @author 挚爱之夕
 * @version 1.0
 * @implSpec 中等
 *
 * @since 2023-09-20 16:18
 */
public class _142环形链表2 {
    //快慢指针
    public ListNode detectCycle(ListNode head) {
        if(head == null || head.next == null) return null;
        ListNode fast = head, slow = head;
        while(fast != null){
            slow = slow.next;
            if(fast.next == null) return null;
            fast = fast.next.next;
            if(slow == fast) {  //有环
                //从头开始和slow向后移动，直到相遇
                ListNode p = head;
                while(p != slow){
                    p = p.next;
                    slow = slow.next;
                }
                return p;
            }
        }
        return null;
    }
}
